﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using System.Web.Routing;
using System.Reflection;

namespace LCA.Community.Web
{
    public class UnityControllerFactory : IControllerFactory
    {
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            var container = MvcApplication.Container;

            Assembly currentAssembly = Assembly.GetExecutingAssembly(); 

            var controllerTypes = from t in currentAssembly.GetTypes() 
                                  where t.Name.Contains(controllerName + "Controller") 
                                  select t; 

            if (controllerTypes.Count() > 0) 
            { 
                return container.Resolve(controllerTypes.First()) as IController; 
            } 
            else 
            { 
                return null; 
            }
        }

        public void ReleaseController(IController controller)
        {
            controller = null;
        }
    }
}